package open.tech.dawn.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import open.tech.dawn.core.service.ICacheService;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.core.io.ClassPathResource;


public class DefaultCacheServiceImpl implements ICacheService {

    private final CacheManager cacheManager;

    public DefaultCacheServiceImpl() {
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cacheManagerFactoryBean.setShared(true);
        cacheManagerFactoryBean.afterPropertiesSet();
        this.cacheManager = cacheManagerFactoryBean.getObject();
    }

    @Override
    public void put(String cacheName, String key, Object value, int expirationSeconds) {
        cacheManager.addCache(cacheName);
        Element element = new Element(key, value);
        element.setTimeToLive(expirationSeconds);
        cacheManager.getCache(cacheName).put(element);
    }

    @Override
    public void put(String cacheName, String key, Object value) {
        cacheManager.addCache(cacheName);
        cacheManager.getCache(cacheName).put(new Element(key, value));
    }

    @Override
    public Object get(String cacheName, String key) {
        Cache cache = cacheManager.getCache(cacheName);
        if(cache == null) {
            return null;
        }
        Element element = cache.get(key);
        if(element == null) {
            return null;
        }
        return element.getObjectValue();
    }

    @Override
    public void remove(String cacheName) {
        cacheManager.removeCache(cacheName);
    }
}
